package com.ljb.utilslibary_master.utils;


import android.content.Context;

import com.google.gson.Gson;
import com.ljb.utilslibrary.commUtils.L;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;


/**
 * Created by ljb on 2017/6/12.
 */

public class AssetsDataTool {

    private static AssetsDataTool tool;

    public static AssetsDataTool init() {
        if (tool == null) {
            tool = new AssetsDataTool();
        }
        return tool;
    }

    /**
     * 读取资源文件中的数据
     *
     * @param c        上下文
     * @param fileName 文件名称
     * @param model    业务bean
     * @return
     */
    public <T> T readData(Context c, String fileName, Class<T> model) {
        try {
            L.e("开始读取" + fileName + "中的模拟数据");
            InputStream is = c.getAssets().open(fileName);
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            Gson gson = new Gson();
            String s = new String(buffer, "utf-8");
            T t = gson.fromJson(s, model);
            L.e(fileName + "文件中的模拟数据读取完毕");
            return t;
        } catch (IOException e) {
            e.printStackTrace();
        }
        throw new RuntimeException("读取错误");
    }

    public <T> T formIS(InputStream is, Class<T> clazz) {
        try {
            //最好在将字节流转换为字符流的时候 进行转码
            BufferedReader bf = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            StringBuffer buffer = new StringBuffer();
            String line;

            while ((line = bf.readLine()) != null) {
                buffer.append(line);
            }

            Gson gson = new Gson();
            T t = gson.fromJson(buffer.toString(), clazz);
            return t;

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        throw new RuntimeException("读取错误");
    }
}
